from flask import Flask, render_template, request, redirect, url_for
import hashlib
import sqlite3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time

app = Flask(__name__)

# 数据库操作相关函数
def create_connection():
    conn = sqlite3.connect('users.db')
    return conn

def create_table(conn):
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            nickname TEXT UNIQUE,
            password TEXT,
            email TEXT,
            activation_code TEXT,
            registration_time INTEGER,
            is_active INTEGER DEFAULT 0
        )
    ''')
    conn.commit()

def insert_user(conn, nickname, password, email, activation_code, registration_time):
    cursor = conn.cursor()
    try:
        cursor.execute('''
            INSERT INTO users (nickname, password, email, activation_code, registration_time)
            VALUES (?,?,?,?,?)
        ''', (nickname, password, email, activation_code, registration_time))
        conn.commit()
        return True
    except sqlite3.IntegrityError:
        return False

def get_user_by_nickname(conn, nickname):
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users WHERE nickname =?', (nickname,))
    return cursor.fetchone()

def update_user_active(conn, nickname):
    cursor = conn.cursor()
    cursor.execute('UPDATE users SET is_active = 1 WHERE nickname =?', (nickname,))
    conn.send()
    conn.commit()

# 邮件发送函数
def send_activation_email(email, nickname, activation_code):
    sender_email = "your_email@example.com"  # 请替换为你的邮箱
    sender_password = "your_email_password"  # 请替换为你的邮箱密码
    receiver_email = email

    msg = MIMEMultipart()
    msg['Subject'] = "激活你的账号"
    msg['From'] = sender_email
    msg['To'] = receiver_email

    link = f"http://127.0.0.1/verify?user={nickname}&code={activation_code}"
    body = f"点击以下链接激活你的账号：{link}"
    msg.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP('smtp.example.com', 587) as server:  # 请根据你的邮箱设置修改SMTP服务器和端口
        server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())

# 路由相关
@app.route('/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        nickname = request.form['nickname']
        password = request.form['password']
        email = request.form['email']

        activation_code = hashlib.sha256(nickname.encode()).hexdigest()
        registration_time = int(time.time())

        conn = create_connection()
        create_table(conn)
        if insert_user(conn, nickname, password, email, activation_code, registration_time):
            send_activation_email(email, nickname, activation_code)
            return "注册成功，激活邮件已发送到你的邮箱。请在一小时内点击邮件中的链接激活账号。"
        else:
            return "注册失败，昵称可能已被使用。"
    return render_template('register.html')

@app.route('/verify', methods=['GET'])
def verify():
    nickname = request.args.get('user')
    code = request.args.get('code')

    conn = create_connection()
    user = get_user_by_nickname(conn, nickname)

    if user:
        stored_code = user[4]
        registration_time = user[5]
        current_time = int(time.time())

        if code == stored_code and current_time - registration_time <= 3600:
            update_user_active(conn, nickname)
            return "账号激活成功！"
        else:
            return "激活链接已过期，请重新注册。"
    else:
        return "无效的激活链接。"

if __name__ == '__main__':
    app.run(debug=True)